using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Drawing;
using WegasManagementSystem.Models;

namespace WegasManagementSystem.Utils
{
    /// <summary>
    /// Excel导入导出帮助类
    /// </summary>
    public static class ExcelHelper
    {
        /// <summary>
        /// 将工资数据导出到Excel
        /// </summary>
        /// <param name="salaryRecords">工资记录列表</param>
        /// <param name="yearMonth">年月</param>
        /// <returns>是否导出成功</returns>
        public static bool ExportSalaryToExcel(List<SalaryRecord> salaryRecords, string yearMonth)
        {
            try
            {
                // 使用SaveFileDialog让用户选择保存文件的位置和名称
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.Filter = "Excel文件(*.xlsx)|*.xlsx|Excel 2003文件(*.xls)|*.xls";
                saveDialog.FileName = $"工资发放明细表_{yearMonth}";
                saveDialog.DefaultExt = ".xlsx";
                saveDialog.AddExtension = true;

                if (saveDialog.ShowDialog() != DialogResult.OK)
                    return false;

                // 这里应该使用Excel组件（如EPPlus, NPOI, Microsoft.Office.Interop.Excel等）
                // 由于VS2012对应.NET 4.5，我们的示例使用简单方式模拟
                using (StreamWriter writer = new StreamWriter(saveDialog.FileName, false, System.Text.Encoding.UTF8))
                {
                    // 写入表头
                    writer.WriteLine("工号,姓名,部门,工资项目,类型,金额,年月");

                    // 写入数据
                    foreach (var record in salaryRecords)
                    {
                        string itemType = record.ItemType == "income" ? "收入项" : "扣款项";
                        writer.WriteLine($"{record.EmpId},{record.EmpName},{record.DeptName},{record.ItemName},{itemType},{record.Amount},{record.YearMonth}");
                    }
                }

                MessageBox.Show("工资数据导出成功！", "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        /// <summary>
        /// 将员工工资单导出为PDF
        /// </summary>
        /// <param name="empId">员工ID</param>
        /// <param name="yearMonth">年月</param>
        /// <param name="salaryRecords">工资记录</param>
        /// <returns>是否导出成功</returns>
        public static bool ExportEmployeeSalaryToPdf(int empId, string yearMonth, List<SalaryRecord> salaryRecords)
        {
            try
            {
                // 使用SaveFileDialog让用户选择保存文件的位置和名称
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.Filter = "PDF文件(*.pdf)|*.pdf";
                saveDialog.FileName = $"工资单_{salaryRecords.FirstOrDefault()?.EmpName}_{yearMonth}";
                saveDialog.DefaultExt = ".pdf";
                saveDialog.AddExtension = true;

                if (saveDialog.ShowDialog() != DialogResult.OK)
                    return false;

                // 在实际应用中，应使用PDF生成库（如iTextSharp）来创建PDF
                // 这里我们仅作示例模拟
                using (StreamWriter writer = new StreamWriter(saveDialog.FileName, false, System.Text.Encoding.UTF8))
                {
                    // 写入一些基本信息作为示例
                    writer.WriteLine($"员工工资单 - {yearMonth}");
                    writer.WriteLine($"姓名: {salaryRecords.FirstOrDefault()?.EmpName}");
                    writer.WriteLine($"部门: {salaryRecords.FirstOrDefault()?.DeptName}");
                    writer.WriteLine($"工号: {empId}");
                    writer.WriteLine("-------------------------------------");
                    writer.WriteLine("工资项目,金额");

                    decimal totalIncome = 0;
                    decimal totalDeduction = 0;

                    // 写入工资项目
                    foreach (var record in salaryRecords)
                    {
                        writer.WriteLine($"{record.ItemName},{record.Amount}");
                        
                        if (record.ItemType == "income")
                            totalIncome += record.Amount;
                        else if (record.ItemType == "deduction")
                            totalDeduction += record.Amount;
                    }

                    writer.WriteLine("-------------------------------------");
                    writer.WriteLine($"收入合计: {totalIncome}");
                    writer.WriteLine($"扣款合计: {totalDeduction}");
                    writer.WriteLine($"实发工资: {totalIncome - totalDeduction}");
                }

                MessageBox.Show("工资单导出成功！", "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        /// <summary>
        /// 从Excel导入工资数据
        /// </summary>
        /// <returns>导入的工资数据</returns>
        public static DataTable ImportSalaryFromExcel()
        {
            DataTable dt = new DataTable();
            try
            {
                OpenFileDialog openDialog = new OpenFileDialog();
                openDialog.Filter = "Excel文件(*.xlsx)|*.xlsx|Excel 2003文件(*.xls)|*.xls|所有文件(*.*)|*.*";
                openDialog.FilterIndex = 1;
                openDialog.RestoreDirectory = true;

                if (openDialog.ShowDialog() != DialogResult.OK)
                    return null;

                // 创建数据表结构
                dt.Columns.Add("工号", typeof(string));
                dt.Columns.Add("姓名", typeof(string));
                dt.Columns.Add("部门", typeof(string));
                dt.Columns.Add("工资项目", typeof(string));
                dt.Columns.Add("类型", typeof(string));
                dt.Columns.Add("金额", typeof(decimal));
                dt.Columns.Add("年月", typeof(string));

                // 在实际应用中，应使用Excel读取库（如EPPlus, NPOI）来读取Excel
                // 这里我们仅作示例模拟
                string[] lines = File.ReadAllLines(openDialog.FileName);
                bool isFirstLine = true;

                foreach (string line in lines)
                {
                    if (isFirstLine)
                    {
                        isFirstLine = false;
                        continue; // 跳过表头
                    }

                    string[] values = line.Split(',');
                    if (values.Length >= 7)
                    {
                        DataRow row = dt.NewRow();
                        row["工号"] = values[0];
                        row["姓名"] = values[1];
                        row["部门"] = values[2];
                        row["工资项目"] = values[3];
                        row["类型"] = values[4];
                        decimal amount;
                        if (decimal.TryParse(values[5], out amount))
                            row["金额"] = amount;
                        else
                            row["金额"] = 0;
                        row["年月"] = values[6];
                        dt.Rows.Add(row);
                    }
                }

                return dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导入失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        /// <summary>
        /// 将DataTable导出到Excel文件
        /// </summary>
        /// <param name="dataTable">要导出的数据表</param>
        /// <param name="filePath">文件保存路径</param>
        /// <returns>是否导出成功</returns>
        public static bool ExportToExcel(DataTable dataTable, string filePath)
        {
            try
            {
                if (dataTable == null || dataTable.Rows.Count == 0 || string.IsNullOrEmpty(filePath))
                    return false;

                // 创建文件夹（如果不存在）
                string directory = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directory))
                    Directory.CreateDirectory(directory);

                // 使用StreamWriter简单模拟Excel文件导出
                // 注意：在实际应用中，建议使用专业的Excel库（如EPPlus、NPOI等）
                using (StreamWriter writer = new StreamWriter(filePath, false, System.Text.Encoding.UTF8))
                {
                    // 写入表头
                    string header = string.Empty;
                    for (int i = 0; i < dataTable.Columns.Count; i++)
                    {
                        if (i > 0)
                            header += ",";
                        header += dataTable.Columns[i].ColumnName;
                    }
                    writer.WriteLine(header);

                    // 写入数据行
                    foreach (DataRow row in dataTable.Rows)
                    {
                        string line = string.Empty;
                        for (int i = 0; i < dataTable.Columns.Count; i++)
                        {
                            if (i > 0)
                                line += ",";

                            object value = row[i];
                            if (value != null)
                            {
                                // 处理特殊字符，如逗号、引号等
                                string cellValue = value.ToString().Replace("\"", "\"\"");
                                if (cellValue.Contains(",") || cellValue.Contains("\"") || cellValue.Contains("\n"))
                                    cellValue = $"\"{cellValue}\"";
                                line += cellValue;
                            }
                        }
                        writer.WriteLine(line);
                    }
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 从Excel导入数据到DataTable
        /// </summary>
        /// <param name="filePath">Excel文件路径</param>
        /// <returns>导入的数据表</returns>
        public static DataTable ImportFromExcel(string filePath)
        {
            DataTable dt = new DataTable();
            try
            {
                if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
                    return null;

                // 创建数据表结构
                dt.Columns.Add("工号", typeof(string));
                dt.Columns.Add("姓名", typeof(string));
                dt.Columns.Add("部门", typeof(string));
                dt.Columns.Add("年份", typeof(string));
                dt.Columns.Add("月份", typeof(string));
                dt.Columns.Add("应出勤天数", typeof(string));
                dt.Columns.Add("实际出勤天数", typeof(string));
                dt.Columns.Add("缺勤天数", typeof(string));
                dt.Columns.Add("加班小时数", typeof(string));
                dt.Columns.Add("迟到次数", typeof(string));
                dt.Columns.Add("早退次数", typeof(string));

                // 在实际应用中，应使用Excel读取库（如EPPlus, NPOI）来读取Excel
                // 这里我们仅作示例模拟
                string[] lines = File.ReadAllLines(filePath);
                bool isFirstLine = true;

                foreach (string line in lines)
                {
                    if (isFirstLine)
                    {
                        isFirstLine = false;
                        continue; // 跳过表头
                    }

                    string[] values = line.Split(',');
                    if (values.Length >= 6) // 至少需要包含工号、姓名、部门、年份、月份、应出勤天数
                    {
                        DataRow row = dt.NewRow();
                        row["工号"] = values[0];
                        row["姓名"] = values[1];
                        row["部门"] = values[2];
                        row["年份"] = values[3];
                        row["月份"] = values[4];
                        row["应出勤天数"] = values[5];
                        
                        if (values.Length > 6)
                            row["实际出勤天数"] = values[6];
                        
                        if (values.Length > 7)
                            row["缺勤天数"] = values[7];
                        
                        if (values.Length > 8)
                            row["加班小时数"] = values[8];
                        
                        if (values.Length > 9)
                            row["迟到次数"] = values[9];
                        
                        if (values.Length > 10)
                            row["早退次数"] = values[10];
                        
                        dt.Rows.Add(row);
                    }
                }

                return dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导入失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }
    }
} 